<?php
namespace My\Model;

use Utuo\UtuoModel;

class DealerModel extends UtuoModel {
	
    // 自动验证
    protected $_validate = array( 
    	array('wechat_uid', 'getWechatUid','设置要设为金牌会员的用户不正确', self::MUST_VALIDATE, 'callback'),
    );
    
    // 自动赋值
    protected $_auto = array(
        array('begin_time', 'strtotime', self::MODEL_BOTH, 'function'),
        array('end_time', 'strtotime', self::MODEL_BOTH, 'function'),
    	array('password', 'hash_pwd', self::MODEL_BOTH, 'function'),
    );
    
    
//     protected function _before_insert(&$data, $options) {
//     	parent::_before_insert($data, $options);
//     }
    
    /**
     * 新增代理商用户后处理
     * @see \Think\Model::_after_insert()
     */
    protected function _after_insert($data, $options) {
        $id = $data[$this->getPk()];
        if ( false !== $id ) {
            /* 设置用户为代理商类型  */
            $wechatUid = $data['wechat_uid'];
            $m = M("WechatUser");
            $wechatUser = $m->where("id=%d", $wechatUid)->find();
            $userRole = new UserRole();
            $type = $userRole->type($wechatUser['type'])->becomeTo(WechatUserModel::USER_TYPE_FRANCHISED_DEALER)->getType();
            $m->where("id=%d", $wechatUid)->save(array('type' => $type, 'dealerTime'=>time())); 
            /* 设置用户申请代理商已通过  */
            if( $applyId = $_REQUEST['applyId'] ) {
            	M("DealerApply")->where(array('cid' => $this->adminId, 'id' => $applyId ))->setField('status', 1);
            }
        }
    }
    
    /**
     * 更新前处理
     * @see \Utuo\UtuoModel::_before_update()
     */
    protected function _before_update(&$data, &$options) {
    	unset($data['wechat_uid']); // 指定的用户id不可修改
    	return parent::_before_update($data, $options);
    }
    
    /**
     * 用户id验证
     */
    protected function getWechatUid() {
    	$id = I('id', 0, "intval");
    	if ( !$id ) { // 添加用户时
    		$wechatUid = I('wechat_uid', 0, "intval");
    		$wechatUser = M("WechatUser a")->join("__DEALER__ b on a.id=b.wechat_uid", "LEFT")->where("a.id=%d", $wechatUid)->field("a.*,b.id as dealerId")->find();
    		if ( $wechatUser ) {
    			$userRole = new UserRole();
    			if ( $wechatUser['dealerId'] and $userRole->type($wechatUser['type'])->is(WechatUserModel::USER_TYPE_FRANCHISED_DEALER) ) {
    				$this->error['wechat_uid'] = "您选择的用户已是金牌会员";
    			} else {
    				return true;
    			}
    		} else {
    			$this->error['wechat_uid'] = "请先选择已绑定的微信用户";
    		}
    		return false;
    	} else { // 修改时
    		return true;
    	}
    }
    
}